package com.example.recyclerviewdemo.diffdemo

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.blankj.utilcode.util.CloneUtils
import com.example.recyclerviewdemo.R
import com.example.recyclerviewdemo.model.bean.ChatBean
import com.example.recyclerviewdemo.utils.DataUtil
import com.example.recyclerviewdemo.utils.MarginItemDecoration
import com.google.android.material.button.MaterialButton
import com.google.gson.reflect.TypeToken

class DiffDemoActivity : AppCompatActivity() {

    /*
    * 添加一个item   怎么绘制
    * 删除 一个item
    *
    *
    * */

    private val chatAdapter by lazy {
        DiffUtilAdapter(this)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_diff_demo)
        initViews()
        initRv()
    }

    private fun initViews() {
        val diffUtil = findViewById<MaterialButton>(R.id.diffUtil)
        diffUtil.setOnClickListener { diffUtilData() }

    }

    private fun diffUtilData() {
        val listType = object : TypeToken<List<ChatBean>>() {}.type
        val listType2 = object : TypeToken<ChatBean>() {}.type
        //深拷贝一个新对象，防止改到原来的列表 oldList
        val newList = CloneUtils.deepClone(chatAdapter.getItems(), listType)
        val newBean = CloneUtils.deepClone(newList[0], listType2)

        newBean.contentText ="修改后的值"
        newList.add(4,newBean)
        chatAdapter.setNewList(newList,true)
    }

    private fun initRv() {

        val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)

        val mutableListOf = mutableListOf<ChatBean>()
        for (i in 0..50) {
            mutableListOf.add(ChatBean(i, DataUtil.getDrawable(i), "聊天对象title$i", "聊天内容$i", 0L))
        }
        chatAdapter.setNewList(mutableListOf)
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = chatAdapter
        recyclerView.addItemDecoration(MarginItemDecoration(this, 2f, 0f, 0f, 0f))

    }

}